/* global plupload */

/**
 Custom module for you to write your own javascript functions
 **/
var OssPluploadCustom = function () {
    /**
     * accessid 
     */
    var accessid = '';
    /**
     * accesskey 
     */
    var accesskey = '';
    /**
     * 已经设置的SKU值 
     */
    var host = '';
    /**
     * 已经设置的SKU值 
     */
    var token = '';
    /**
     * 已经设置的SKU值 
     */
    var policyBase64 = '';
    /**
     * 已经设置的SKU值 
     */
    var signature = '';
    /**
     * 已经设置的SKU值 
     */
    var callbackbody = '';
    /**
     * 已经设置的SKU值 
     */
    var filename = '';
    /**
     * 已经设置的SKU值 
     */
    var key = '';
    /**
     * 已经设置的SKU值 
     */
    var expire = 0;
    /**
     * 已经设置的SKU值 
     */
    var g_object_name = '';
    /**
     * 对象随机命名 
     */
    var g_object_name_type = 'random_name';
    /**
     * 已经设置的SKU值 
     */
    var timestamp = Date.parse(new Date()) / 1000;
    /**
     * 已经设置的SKU值 
     */
    var now = timestamp;

    var fileTypes = /^video\/.*$/;

    var get_signature = function () {
        // 可以判断当前expire是否超过了当前时间， 如果超过了当前时间， 就重新取一下，3s 作为缓冲。
        now = timestamp = Date.parse(new Date()) / 1000;
        if (expire < now + 3) {
            var body = {};
            $.ajax({
                url: '/attachs/authent',
                type: 'GET',
                async: false,
                dataType: 'json',
                success: function (data) {
                    body = data;
                },
                error: function (json) {
                    alert("Your browser does not support XMLHTTP.");
                }
            });
            if (body) {
                host = body.host;
                token = body.token;
                policyBase64 = body.policy;
                accessid = body.accessid;
                signature = body.signature;
                expire = parseInt(body.expire);
                callbackbody = body.callback;
                key = body.dir;
                return true;
            } else {
                return false;
            }
        }
        return false;
    };

    var random_string = function (len) {
        len = len || 32;
        var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
        var maxPos = chars.length;
        var pwd = '';
        for (i = 0; i < len; i++) {
            pwd += chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
    };

    var get_suffix = function (filename) {
        pos = filename.lastIndexOf('.');
        suffix = '';
        if (pos !== -1) {
            suffix = filename.substring(pos);
        }
        return suffix;
    };

    var calculate_object_name = function (filename) {
        if (g_object_name_type === 'local_name') {
            g_object_name += "${filename}";
        } else if (g_object_name_type === 'random_name') {
            suffix = get_suffix(filename);
            g_object_name = key + random_string(10) + suffix;
        }
        return '';
    };

    var get_uploaded_object_name = function (filename) {
        if (g_object_name_type === 'local_name') {
            tmp_name = g_object_name;
            tmp_name = tmp_name.replace("${filename}", filename);
            return tmp_name;
        } else if (g_object_name_type === 'random_name') {
            return g_object_name;
        }
    };

    var set_upload_param = function (up, filename, ret) {
        if (ret === false) {
            ret = get_signature();
        }
        g_object_name = key;
        if (filename !== '') {
            suffix = get_suffix(filename);
            calculate_object_name(filename);
        }

        var newsparams = {
            'key': g_object_name,
            'policy': policyBase64,
            'OSSAccessKeyId': accessid,
            'x-oss-security-token': token,
            'success_action_status': '200', //让服务端返回200,不然，默认会返回204
            'callback': callbackbody,
            'signature': signature
        };
        up.setOption({
            url: host,
            multipart_params: newsparams
        });

        up.start();
    };

    var previewFile = function (file, callback) {
        var _previewElement = null;
        var url = URL.createObjectURL(file.getNative());
        if (fileTypes.test(file.type)) {
            _previewElement = document.createElement('video');
            _previewElement.controls = true;
        } else {
            _previewElement = document.createElement('img');
        }
        _previewElement.src = url;

        callback(_previewElement)
    };

    var previewProgress = function (file, callback) {
        var progressElement = document.createElement('div');
        progressElement.id = 'progress' + file.id;
        progressElement.className = 'progress';
        var progressBarElement = document.createElement('div');
        progressBarElement.className = 'progress-bar';
        progressBarElement.style.width = '0%';
        progressBarElement.innerHTML = '0%';
        progressBarElement.setAttribute('role', 'progressbar');
        progressBarElement.setAttribute('aria-valuenow', '0');
        progressBarElement.setAttribute('aria-valuemin', '0');
        progressBarElement.setAttribute('aria-valuemax', '100');
        progressElement.append(progressBarElement);
        callback(progressElement)
    };

    var dumpInfo = function () {

    };


    var uploadSave = function (file) {
        $.ajax({
            url: '/attachs/weboss',
            type: 'POST',
            data: {
                path: get_uploaded_object_name(file.name),
                size: file.size
            },
            dataType: 'json',
            success: function (data) {
                console.log(data);
                location.reload();
            },
            error: function (json) {
                alert("Your browser does not support XMLHTTP.");
            }
        });
    };

    return {
        init: function () {
            //SKU属性发生改变时，进行表格创建
            var uploader = new plupload.Uploader({
                runtimes: 'html5,flash,silverlight,html4',
                browse_button: 'selectfiles',
                multi_selection: false,
                container: document.getElementById('container'),
                flash_swf_url: 'lib/plupload-2.1.2/js/Moxie.swf',
                silverlight_xap_url: 'lib/plupload-2.1.2/js/Moxie.xap',
                url: 'http://oss.aliyuncs.com',
                filters: {
                    mime_types: [
                        {title: "Video files", extensions: "mp4"}
                    ],
                    max_file_size: '100mb', //最大只能上传100mb的文件
                    prevent_duplicates: true //不允许选取重复文件
                },
                init: {
                    PostInit: function () {
                        document.getElementById('preview-container').innerHTML = '';
                        document.getElementById('postfiles').onclick = function () {
                            set_upload_param(uploader, '', false);
                            return false;
                        };
                    },
                    FilesAdded: function (up, files) {
                        plupload.each(files, function (file) {
                            var preview = document.getElementById('preview-container');
                            var el = document.createElement('div');
                            el.id = file.id;
                            el.className = 'preview-item';
                            el.innerHTML = '<div class="file-preview">'
                                    + '<div class="square-block">'
                                    + '<div class="square-block-dummy"></div>'
                                    + '<div class="square-block-box"></div>'
                                    + '</div>'
                                    + '</div>'
                                    + '<div class="file-info">'
                                    + '<h3>' + file.name + '</h3>'
                                    + '<p>' + plupload.formatSize(file.size) + '</p>'
                                    + '<b></b>'
                                    + '</div>';
                            previewProgress(file, function (element) {
                                el.appendChild(element);
                            });
                            document.getElementById('postfiles').style.display = 'inline-block';

                            previewFile(file, function (element) {
                                var box = el.getElementsByClassName('square-block-box')[0];
                                box.appendChild(element);
                                preview.appendChild(el);
                            });
                        });
                    },

                    BeforeUpload: function (up, file) {
                        set_upload_param(up, file.name, true);
                    },

                    UploadProgress: function (up, file) {
                        var prog = document.getElementById('progress' + file.id);
                        var progBar = prog.getElementsByTagName('div')[0];
                        progBar.style.width = file.percent + '%';
                        progBar.innerHTML = file.percent + '%';
                        progBar.setAttribute('aria-valuenow', file.percent);
                    },

                    FileUploaded: function (up, file, info) {
                        if (info.status === 200) {
                            uploadSave(file)
                        } else if (info.status === 203) {
                            document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '上传到OSS成功，但是oss访问用户设置的上传回调服务器失败，失败原因是:'
                                    + info.response;
                        } else {
                            document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = info.response;
                        }
                    },

                    Error: function (up, err) {
                        if (err.code === -600) {
                            document.getElementById('console').appendChild(document.createTextNode("\n选择的文件太大了,可以根据应用情况，在upload.js 设置一下上传的最大大小"));
                        } else if (err.code === -601) {
                            document.getElementById('console').appendChild(document.createTextNode("\n选择的文件后缀不对,可以根据应用情况，在upload.js进行设置可允许的上传文件类型"));
                        } else if (err.code === -602) {
                            document.getElementById('console').appendChild(document.createTextNode("\n这个文件已经上传过一遍了"));
                        } else {
                            document.getElementById('console').appendChild(document.createTextNode("\nError xml:" + err.response));
                        }
                    }
                }
            });

            uploader.init();
        }
    };
}();

OssPluploadCustom.init();